import React, { useEffect, useState } from 'react';
import AvatarDisplay from '@/components/work-modal/components/AvatarDisplay';
import styles from '../index.module.scss';
import { SvgIcon } from '@/components/icon';
import { Divider, Tooltip } from 'antd';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import orchestrationService from '@/api/services/orchestrationService';
import { AppWorkbenchType } from '@/common/app/constants';
import useWindowWidth from '@/hooks/event/use-window-width';

export interface FusionAppItem {
  appId: string;
  name: string;
  intro: string;
  appLogo?: string;
  icon?: string;
}

interface FusionAppListProps {
  apps?: FusionAppItem[];
  className?: string;
}

const FusionAppList: React.FC<FusionAppListProps> = () => {
  const { setFusionAppId, setSubAppDetail, setShowKeyAgent, showKeyAgent, fusionAgentSquare } =
    useOrchestrationStore();
  const [apps, setApps] = useState(fusionAgentSquare);

  useEffect(() => {
    setApps(fusionAgentSquare || []);
  }, [fusionAgentSquare]);

  const handleAppClick = (id: string) => {
    setFusionAppId(id);
    orchestrationService.getAppDetailV2(id, AppWorkbenchType.public).then((app) => {
      setSubAppDetail(app);
    });
  };

  const { isPc } = useWindowWidth();

  // if (!apps || apps.length === 0) return null;
  return (
    <div
      className={`fusion-app-list flex cursor-pointer flex-col rounded-br-[16px] rounded-tr-[16px] bg-[#fff] shadow-lg`}
      style={{
        position: 'absolute',
        top: 'calc(50% - 240px)',
        left: 0,
        // transform: 'translate(-50%, -240px)',
        zIndex: 1000,
      }}
    >
      {(isPc || !showKeyAgent) && (<div
        className={`flex h-[48px] w-[44px] items-center py-2 ${isPc ? 'justify-start' : 'justify-center'}`}
        onClick={() => {
          setShowKeyAgent(!showKeyAgent);
        }}
      >
        <SvgIcon className="flex items-center justify-center" icon={showKeyAgent ? 'ai-chat-close' : 'ai-chat-open'} size={32} />
      </div>)}

      {(isPc || !showKeyAgent) && <>
        {apps && apps?.length > 0 &&
          <div className={`flex items-center pr-4 ${isPc ? 'justify-start' : 'justify-center'}`}>
            <Divider style={{ margin: '2px' }} />
          </div>
        }

        {apps?.slice(0, 5).map((app) => (
          <Tooltip key={app.appId} title={app.appName} placement="right">
            <div
              className={`flex cursor-pointer items-center gap-3 py-2 ${isPc ? 'justify-start' : 'justify-center'}`}
              onClick={() => handleAppClick(app.appId)}
            >
              <AvatarDisplay
                src={app.avatar || 'default'}
                size={32}
                className="h-[32px] w-[32px] flex-shrink-0"
              />
            </div>
          </Tooltip>
        ))}
      </>}

    </div>
  );
};

export default FusionAppList;
